﻿namespace Leetcode.N0060;
public class Solution
{
    public string GetPermutation(int n, int k)
    {
        var list = new List<int>();
        for (int i = 1; i <= n; i++)
        {
            list.Add(i);
        }
        var ans = new System.Text.StringBuilder();
        while (list.Count > 0)
        {
            var count = this.Factorial(list.Count - 1);
            var index = (int)Math.Floor((double)(k - 1) / count);
            ans.Append(list[index]);
            list.RemoveAt(index);
            k = k - count * index;
        }
        return ans.ToString();
    }

    private int Factorial(int n)
    {
        var c = 1;
        while (n > 0)
        {
            c = c * n;
            n--;
        }
        return c;
    }
}